package cn.yll.common.utils;

import cn.yll.common.exception.BsErrEnum;
import cn.yll.common.exception.BsException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Objects;

/**
 * 对象拷贝工具类 使用spring
 * @author yangll
 */
@Slf4j
public class CopierUtil {

    /**
     * 类型转换工具
     * @author yangll
     */
    public static <T> T convertT(Object o, Class<T> tClass) {
        if (Objects.isNull(o)) {
            return null;
        }
        try {
            T t = tClass.getDeclaredConstructor().newInstance();
            BeanUtils.copyProperties(o, t);
            return t;
        } catch (Exception e) {
            log.error("{}类型转换{}异常", o.getClass().getSimpleName(), tClass.getSimpleName(), e);
            throw new BsException(BsErrEnum.SYSTEM_ERROR);
        }
    }

    /**
     * 集合类型转换工具
     * @author yangll
     */
    public static <T> List<T> convertList(List<?> list, Class<T> tClass) {
        if (CollectionUtils.isEmpty(list)) {
            return Collections.EMPTY_LIST;
        }
        try {
            List<T> res = new ArrayList<>(list.size());
            list.forEach(e -> res.add(convertT(e, tClass)));
            return res;
        } catch (Exception e) {
            log.error("{}类型转换{}异常", list.get(0).getClass().getSimpleName(), tClass.getSimpleName(), e);
            throw new BsException(BsErrEnum.SYSTEM_ERROR);
        }
    }
}
